package pg

import (
	"fmt"
	"strings"
)

var (
	// systemDatabases is the list of system or internal databases.
	systemDatabases = map[string]bool{
		// Skip internal databases from cloud service providers
		// see https://github.com/bytebase/bytebase/issues/30
		// aws
		"rdsadmin": true,
		// gcp
		"cloudsql":      true,
		"cloudsqladmin": true,
		"alloydbadmin":  true,
		// system templates.
		"template0": true,
		"template1": true,
	}

	// systemFunctions is the list of built-in functions.
	// generated from https://sourcegraph.com/github.com/postgres/postgres/-/blob/doc/src/sgml/func.sgml.
	systemFunctions = map[string]bool{
		"abbrev":                                 true,
		"abs":                                    true,
		"acldefault":                             true,
		"aclexplode":                             true,
		"acos":                                   true,
		"acosd":                                  true,
		"acosh":                                  true,
		"age":                                    true,
		"any":                                    true,
		"any_value":                              true,
		"area":                                   true,
		"array_agg":                              true,
		"array_append":                           true,
		"array_cat":                              true,
		"array_dims":                             true,
		"array_fill":                             true,
		"array_length":                           true,
		"array_lower":                            true,
		"array_ndims":                            true,
		"array_position":                         true,
		"array_positions":                        true,
		"array_prepend":                          true,
		"array_remove":                           true,
		"array_replace":                          true,
		"array_sample":                           true,
		"array_shuffle":                          true,
		"array_to_json":                          true,
		"array_to_string":                        true,
		"array_to_tsvector":                      true,
		"array_upper":                            true,
		"ascii":                                  true,
		"asin":                                   true,
		"asind":                                  true,
		"asinh":                                  true,
		"atan":                                   true,
		"atan2":                                  true,
		"atan2d":                                 true,
		"atand":                                  true,
		"atanh":                                  true,
		"avg":                                    true,
		"bit_and":                                true,
		"bit_count":                              true,
		"bit_length":                             true,
		"bit_or":                                 true,
		"bit_xor":                                true,
		"bool_and":                               true,
		"bool_or":                                true,
		"bound_box":                              true,
		"box":                                    true,
		"brin_desummarize_range":                 true,
		"brin_summarize_new_values":              true,
		"brin_summarize_range":                   true,
		"broadcast":                              true,
		"btrim":                                  true,
		"cardinality":                            true,
		"cbrt":                                   true,
		"ceil":                                   true,
		"ceiling":                                true,
		"center":                                 true,
		"char_length":                            true,
		"character_length":                       true,
		"chr":                                    true,
		"circle":                                 true,
		"clock_timestamp":                        true,
		"coalesce":                               true,
		"col_description":                        true,
		"collation for":                          true,
		"concat":                                 true,
		"concat_ws":                              true,
		"convert":                                true,
		"convert_from":                           true,
		"convert_to":                             true,
		"corr":                                   true,
		"cos":                                    true,
		"cosd":                                   true,
		"cosh":                                   true,
		"cot":                                    true,
		"cotd":                                   true,
		"count":                                  true,
		"covar_pop":                              true,
		"covar_samp":                             true,
		"cume_dist":                              true,
		"current_catalog":                        true,
		"current_database":                       true,
		"current_date":                           true,
		"current_query":                          true,
		"current_role":                           true,
		"current_schema":                         true,
		"current_schemas":                        true,
		"current_setting":                        true,
		"current_time":                           true,
		"current_timestamp":                      true,
		"current_user":                           true,
		"currval":                                true,
		"cursor_to_xml":                          true,
		"cursor_to_xmlschema":                    true,
		"database_to_xml":                        true,
		"database_to_xml_and_xmlschema":          true,
		"database_to_xmlschema":                  true,
		"date_add":                               true,
		"date_bin":                               true,
		"date_part":                              true,
		"date_subtract":                          true,
		"date_trunc":                             true,
		"decode":                                 true,
		"degrees":                                true,
		"dense_rank":                             true,
		"diagonal":                               true,
		"diameter":                               true,
		"div":                                    true,
		"encode":                                 true,
		"enum_first":                             true,
		"enum_last":                              true,
		"enum_range":                             true,
		"erf":                                    true,
		"erfc":                                   true,
		"every":                                  true,
		"exp":                                    true,
		"extract":                                true,
		"factorial":                              true,
		"family":                                 true,
		"first_value":                            true,
		"floor":                                  true,
		"format":                                 true,
		"format_type":                            true,
		"gcd":                                    true,
		"gen_random_uuid":                        true,
		"generate_series":                        true,
		"generate_subscripts":                    true,
		"get_bit":                                true,
		"get_byte":                               true,
		"get_current_ts_config":                  true,
		"gin_clean_pending_list":                 true,
		"greatest":                               true,
		"grouping":                               true,
		"has_any_column_privilege":               true,
		"has_column_privilege":                   true,
		"has_database_privilege":                 true,
		"has_foreign_data_wrapper_privilege":     true,
		"has_function_privilege":                 true,
		"has_language_privilege":                 true,
		"has_parameter_privilege":                true,
		"has_schema_privilege":                   true,
		"has_sequence_privilege":                 true,
		"has_server_privilege":                   true,
		"has_table_privilege":                    true,
		"has_tablespace_privilege":               true,
		"has_type_privilege":                     true,
		"height":                                 true,
		"host":                                   true,
		"hostmask":                               true,
		"icu_unicode_version":                    true,
		"ilike":                                  true,
		"inet_client_addr":                       true,
		"inet_client_port":                       true,
		"inet_merge":                             true,
		"inet_same_family":                       true,
		"inet_server_addr":                       true,
		"inet_server_port":                       true,
		"initcap":                                true,
		"isclosed":                               true,
		"isempty":                                true,
		"isfinite":                               true,
		"isopen":                                 true,
		"json":                                   true,
		"json[b]_populate_record":                true,
		"json_agg":                               true,
		"json_agg_strict":                        true,
		"json_array":                             true,
		"json_array_elements":                    true,
		"json_array_elements_text":               true,
		"json_array_length":                      true,
		"json_arrayagg":                          true,
		"json_build_array":                       true,
		"json_build_object":                      true,
		"json_each":                              true,
		"json_each_text":                         true,
		"json_exists":                            true,
		"json_extract_path":                      true,
		"json_extract_path_text":                 true,
		"json_object":                            true,
		"json_object_agg":                        true,
		"json_object_agg_strict":                 true,
		"json_object_agg_unique":                 true,
		"json_object_agg_unique_strict":          true,
		"json_object_keys":                       true,
		"json_objectagg":                         true,
		"json_populate_record":                   true,
		"json_populate_recordset":                true,
		"json_query":                             true,
		"json_scalar":                            true,
		"json_serialize":                         true,
		"json_strip_nulls":                       true,
		"json_table":                             true,
		"json_to_record":                         true,
		"json_to_recordset":                      true,
		"json_to_tsvector":                       true,
		"json_typeof":                            true,
		"json_value":                             true,
		"jsonb_agg":                              true,
		"jsonb_agg_strict":                       true,
		"jsonb_array_elements":                   true,
		"jsonb_array_elements_text":              true,
		"jsonb_array_length":                     true,
		"jsonb_build_array":                      true,
		"jsonb_build_object":                     true,
		"jsonb_each":                             true,
		"jsonb_each_text":                        true,
		"jsonb_extract_path":                     true,
		"jsonb_extract_path_text":                true,
		"jsonb_insert":                           true,
		"jsonb_object":                           true,
		"jsonb_object_agg":                       true,
		"jsonb_object_agg_strict":                true,
		"jsonb_object_agg_unique":                true,
		"jsonb_object_agg_unique_strict":         true,
		"jsonb_object_keys":                      true,
		"jsonb_path_exists":                      true,
		"jsonb_path_exists_tz":                   true,
		"jsonb_path_match":                       true,
		"jsonb_path_match_tz":                    true,
		"jsonb_path_query":                       true,
		"jsonb_path_query_array":                 true,
		"jsonb_path_query_array_tz":              true,
		"jsonb_path_query_first":                 true,
		"jsonb_path_query_first_tz":              true,
		"jsonb_path_query_tz":                    true,
		"jsonb_populate_record":                  true,
		"jsonb_populate_record_valid":            true,
		"jsonb_populate_recordset":               true,
		"jsonb_pretty":                           true,
		"jsonb_set":                              true,
		"jsonb_set_lax":                          true,
		"jsonb_strip_nulls":                      true,
		"jsonb_to_record":                        true,
		"jsonb_to_recordset":                     true,
		"jsonb_to_tsvector":                      true,
		"jsonb_typeof":                           true,
		"justify_days":                           true,
		"justify_hours":                          true,
		"justify_interval":                       true,
		"lag":                                    true,
		"last_value":                             true,
		"lastval":                                true,
		"lcm":                                    true,
		"lead":                                   true,
		"least":                                  true,
		"left":                                   true,
		"length":                                 true,
		"like":                                   true,
		"line":                                   true,
		"ln":                                     true,
		"localtime":                              true,
		"localtimestamp":                         true,
		"log":                                    true,
		"log10":                                  true,
		"lower":                                  true,
		"lower_inc":                              true,
		"lower_inf":                              true,
		"lpad":                                   true,
		"lseg":                                   true,
		"ltrim":                                  true,
		"macaddr8_set7bit":                       true,
		"make_date":                              true,
		"make_interval":                          true,
		"make_time":                              true,
		"make_timestamp":                         true,
		"make_timestamptz":                       true,
		"makeaclitem":                            true,
		"masklen":                                true,
		"max":                                    true,
		"md5":                                    true,
		"merge_action":                           true,
		"min":                                    true,
		"min_scale":                              true,
		"mod":                                    true,
		"mode":                                   true,
		"multirange":                             true,
		"mxid_age":                               true,
		"netmask":                                true,
		"network":                                true,
		"nextval":                                true,
		"normalize":                              true,
		"not like":                               true,
		"now":                                    true,
		"npoints":                                true,
		"nth_value":                              true,
		"ntile":                                  true,
		"nullif":                                 true,
		"num_nonnulls":                           true,
		"num_nulls":                              true,
		"numnode":                                true,
		"nvl":                                    true,
		"obj_description":                        true,
		"octet_length":                           true,
		"overlay":                                true,
		"parse_ident":                            true,
		"path":                                   true,
		"pclose":                                 true,
		"percent_rank":                           true,
		"percentile_cont":                        true,
		"percentile_disc":                        true,
		"pg_advisory_lock":                       true,
		"pg_advisory_lock_shared":                true,
		"pg_advisory_unlock":                     true,
		"pg_advisory_unlock_all":                 true,
		"pg_advisory_unlock_shared":              true,
		"pg_advisory_xact_lock":                  true,
		"pg_advisory_xact_lock_shared":           true,
		"pg_available_wal_summaries":             true,
		"pg_backend_pid":                         true,
		"pg_backup_start":                        true,
		"pg_backup_stop":                         true,
		"pg_basetype":                            true,
		"pg_blocking_pids":                       true,
		"pg_cancel_backend":                      true,
		"pg_char_to_encoding":                    true,
		"pg_client_encoding":                     true,
		"pg_collation_actual_version":            true,
		"pg_collation_is_visible":                true,
		"pg_column_compression":                  true,
		"pg_column_size":                         true,
		"pg_column_toast_chunk_id":               true,
		"pg_conf_load_time":                      true,
		"pg_control_checkpoint":                  true,
		"pg_control_init":                        true,
		"pg_control_recovery":                    true,
		"pg_control_system":                      true,
		"pg_conversion_is_visible":               true,
		"pg_copy_logical_replication_slot":       true,
		"pg_copy_physical_replication_slot":      true,
		"pg_create_logical_replication_slot":     true,
		"pg_create_physical_replication_slot":    true,
		"pg_create_restore_point":                true,
		"pg_current_logfile":                     true,
		"pg_current_snapshot":                    true,
		"pg_current_wal_flush_lsn":               true,
		"pg_current_wal_insert_lsn":              true,
		"pg_current_wal_lsn":                     true,
		"pg_current_xact_id":                     true,
		"pg_current_xact_id_if_assigned":         true,
		"pg_database_collation_actual_version":   true,
		"pg_database_size":                       true,
		"pg_describe_object":                     true,
		"pg_drop_replication_slot":               true,
		"pg_encoding_to_char":                    true,
		"pg_event_trigger_ddl_commands":          true,
		"pg_event_trigger_dropped_objects":       true,
		"pg_event_trigger_table_rewrite_oid":     true,
		"pg_event_trigger_table_rewrite_reason":  true,
		"pg_export_snapshot":                     true,
		"pg_filenode_relation":                   true,
		"pg_function_is_visible":                 true,
		"pg_get_catalog_foreign_keys":            true,
		"pg_get_constraintdef":                   true,
		"pg_get_expr":                            true,
		"pg_get_function_arguments":              true,
		"pg_get_function_identity_arguments":     true,
		"pg_get_function_result":                 true,
		"pg_get_functiondef":                     true,
		"pg_get_indexdef":                        true,
		"pg_get_keywords":                        true,
		"pg_get_object_address":                  true,
		"pg_get_owned_sequence":                  true,
		"pg_get_partkeydef":                      true,
		"pg_get_ruledef":                         true,
		"pg_get_serial_sequence":                 true,
		"pg_get_statisticsobjdef":                true,
		"pg_get_triggerdef":                      true,
		"pg_get_userbyid":                        true,
		"pg_get_viewdef":                         true,
		"pg_get_wal_replay_pause_state":          true,
		"pg_get_wal_resource_managers":           true,
		"pg_get_wal_summarizer_state":            true,
		"pg_has_role":                            true,
		"pg_identify_object":                     true,
		"pg_identify_object_as_address":          true,
		"pg_import_system_collations":            true,
		"pg_index_column_has_property":           true,
		"pg_index_has_property":                  true,
		"pg_indexam_has_property":                true,
		"pg_indexes_size":                        true,
		"pg_input_error_info":                    true,
		"pg_input_is_valid":                      true,
		"pg_is_in_recovery":                      true,
		"pg_is_other_temp_schema":                true,
		"pg_is_wal_replay_paused":                true,
		"pg_jit_available":                       true,
		"pg_last_committed_xact":                 true,
		"pg_last_wal_receive_lsn":                true,
		"pg_last_wal_replay_lsn":                 true,
		"pg_last_xact_replay_timestamp":          true,
		"pg_listening_channels":                  true,
		"pg_log_backend_memory_contexts":         true,
		"pg_log_standby_snapshot":                true,
		"pg_logical_emit_message":                true,
		"pg_logical_slot_get_binary_changes":     true,
		"pg_logical_slot_get_changes":            true,
		"pg_logical_slot_peek_binary_changes":    true,
		"pg_logical_slot_peek_changes":           true,
		"pg_ls_archive_statusdir":                true,
		"pg_ls_dir":                              true,
		"pg_ls_logdir":                           true,
		"pg_ls_logicalmapdir":                    true,
		"pg_ls_logicalsnapdir":                   true,
		"pg_ls_replslotdir":                      true,
		"pg_ls_tmpdir":                           true,
		"pg_ls_waldir":                           true,
		"pg_mcv_list_items":                      true,
		"pg_my_temp_schema":                      true,
		"pg_notification_queue_usage":            true,
		"pg_opclass_is_visible":                  true,
		"pg_operator_is_visible":                 true,
		"pg_opfamily_is_visible":                 true,
		"pg_options_to_table":                    true,
		"pg_partition_ancestors":                 true,
		"pg_partition_root":                      true,
		"pg_partition_tree":                      true,
		"pg_postmaster_start_time":               true,
		"pg_promote":                             true,
		"pg_read_binary_file":                    true,
		"pg_read_file":                           true,
		"pg_relation_filenode":                   true,
		"pg_relation_filepath":                   true,
		"pg_relation_size":                       true,
		"pg_reload_conf":                         true,
		"pg_replication_origin_advance":          true,
		"pg_replication_origin_create":           true,
		"pg_replication_origin_drop":             true,
		"pg_replication_origin_oid":              true,
		"pg_replication_origin_progress":         true,
		"pg_replication_origin_session_is_setup": true,
		"pg_replication_origin_session_progress": true,
		"pg_replication_origin_session_reset":    true,
		"pg_replication_origin_session_setup":    true,
		"pg_replication_origin_xact_reset":       true,
		"pg_replication_origin_xact_setup":       true,
		"pg_replication_slot_advance":            true,
		"pg_rotate_logfile":                      true,
		"pg_safe_snapshot_blocking_pids":         true,
		"pg_settings_get_flags":                  true,
		"pg_size_bytes":                          true,
		"pg_size_pretty":                         true,
		"pg_sleep":                               true,
		"pg_sleep_for":                           true,
		"pg_sleep_until":                         true,
		"pg_snapshot_xip":                        true,
		"pg_snapshot_xmax":                       true,
		"pg_snapshot_xmin":                       true,
		"pg_split_walfile_name":                  true,
		"pg_stat_file":                           true,
		"pg_statistics_obj_is_visible":           true,
		"pg_switch_wal":                          true,
		"pg_sync_replication_slots":              true,
		"pg_table_is_visible":                    true,
		"pg_table_size":                          true,
		"pg_tablespace_databases":                true,
		"pg_tablespace_location":                 true,
		"pg_tablespace_size":                     true,
		"pg_terminate_backend":                   true,
		"pg_total_relation_size":                 true,
		"pg_trigger_depth":                       true,
		"pg_try_advisory_lock":                   true,
		"pg_try_advisory_lock_shared":            true,
		"pg_try_advisory_xact_lock":              true,
		"pg_try_advisory_xact_lock_shared":       true,
		"pg_ts_config_is_visible":                true,
		"pg_ts_dict_is_visible":                  true,
		"pg_ts_parser_is_visible":                true,
		"pg_ts_template_is_visible":              true,
		"pg_type_is_visible":                     true,
		"pg_typeof":                              true,
		"pg_visible_in_snapshot":                 true,
		"pg_wal_lsn_diff":                        true,
		"pg_wal_replay_pause":                    true,
		"pg_wal_replay_resume":                   true,
		"pg_wal_replay_wait":                     true,
		"pg_wal_summary_contents":                true,
		"pg_walfile_name":                        true,
		"pg_walfile_name_offset":                 true,
		"pg_xact_commit_timestamp":               true,
		"pg_xact_commit_timestamp_origin":        true,
		"pg_xact_status":                         true,
		"phraseto_tsquery":                       true,
		"pi":                                     true,
		"plainto_tsquery":                        true,
		"point":                                  true,
		"polygon":                                true,
		"popen":                                  true,
		"position":                               true,
		"power":                                  true,
		"query_to_xml":                           true,
		"query_to_xml_and_xmlschema":             true,
		"query_to_xmlschema":                     true,
		"querytree":                              true,
		"quote_ident":                            true,
		"quote_literal":                          true,
		"quote_nullable":                         true,
		"radians":                                true,
		"radius":                                 true,
		"random":                                 true,
		"random_normal":                          true,
		"range_agg":                              true,
		"range_intersect_agg":                    true,
		"range_merge":                            true,
		"rank":                                   true,
		"regexp_count":                           true,
		"regexp_instr":                           true,
		"regexp_like":                            true,
		"regexp_match":                           true,
		"regexp_matches":                         true,
		"regexp_replace":                         true,
		"regexp_split_to_array":                  true,
		"regexp_split_to_table":                  true,
		"regexp_substr":                          true,
		"regr_avgx":                              true,
		"regr_avgy":                              true,
		"regr_count":                             true,
		"regr_intercept":                         true,
		"regr_r2":                                true,
		"regr_slope":                             true,
		"regr_sxx":                               true,
		"regr_sxy":                               true,
		"regr_syy":                               true,
		"repeat":                                 true,
		"replace":                                true,
		"reverse":                                true,
		"right":                                  true,
		"round":                                  true,
		"row_number":                             true,
		"row_security_active":                    true,
		"row_to_json":                            true,
		"rpad":                                   true,
		"rtrim":                                  true,
		"scale":                                  true,
		"schema_to_xml":                          true,
		"schema_to_xml_and_xmlschema":            true,
		"schema_to_xmlschema":                    true,
		"session_user":                           true,
		"set_bit":                                true,
		"set_byte":                               true,
		"set_config":                             true,
		"set_masklen":                            true,
		"setseed":                                true,
		"setval":                                 true,
		"setweight":                              true,
		"sha224":                                 true,
		"sha256":                                 true,
		"sha384":                                 true,
		"sha512":                                 true,
		"shobj_description":                      true,
		"sign":                                   true,
		"similar to":                             true,
		"sin":                                    true,
		"sind":                                   true,
		"sinh":                                   true,
		"slope":                                  true,
		"some":                                   true,
		"split_part":                             true,
		"sprintf":                                true,
		"sqrt":                                   true,
		"starts_with":                            true,
		"statement_timestamp":                    true,
		"stddev":                                 true,
		"stddev_pop":                             true,
		"stddev_samp":                            true,
		"string":                                 true,
		"string_agg":                             true,
		"string_to_array":                        true,
		"string_to_table":                        true,
		"strip":                                  true,
		"strpos":                                 true,
		"substr":                                 true,
		"substring":                              true,
		"sum":                                    true,
		"suppress_redundant_updates_trigger":     true,
		"switch":                                 true,
		"system_user":                            true,
		"table_to_xml":                           true,
		"table_to_xml_and_xmlschema":             true,
		"table_to_xmlschema":                     true,
		"tan":                                    true,
		"tand":                                   true,
		"tanh":                                   true,
		"text":                                   true,
		"timeofday":                              true,
		"timezone":                               true,
		"to_ascii":                               true,
		"to_bin":                                 true,
		"to_char":                                true,
		"to_date":                                true,
		"to_hex":                                 true,
		"to_json":                                true,
		"to_jsonb":                               true,
		"to_number":                              true,
		"to_oct":                                 true,
		"to_regclass":                            true,
		"to_regcollation":                        true,
		"to_regnamespace":                        true,
		"to_regoper":                             true,
		"to_regoperator":                         true,
		"to_regproc":                             true,
		"to_regprocedure":                        true,
		"to_regrole":                             true,
		"to_regtype":                             true,
		"to_regtypemod":                          true,
		"to_timestamp":                           true,
		"to_tsquery":                             true,
		"to_tsvector":                            true,
		"transaction_timestamp":                  true,
		"translate":                              true,
		"trim":                                   true,
		"trim_array":                             true,
		"trim_scale":                             true,
		"trunc":                                  true,
		"ts_debug":                               true,
		"ts_delete":                              true,
		"ts_filter":                              true,
		"ts_headline":                            true,
		"ts_lexize":                              true,
		"ts_parse":                               true,
		"ts_rank":                                true,
		"ts_rank_cd":                             true,
		"ts_rewrite":                             true,
		"ts_stat":                                true,
		"ts_token_type":                          true,
		"tsquery_phrase":                         true,
		"tsvector_to_array":                      true,
		"tsvector_update_trigger":                true,
		"tsvector_update_trigger_column":         true,
		"txid_current":                           true,
		"txid_current_if_assigned":               true,
		"txid_current_snapshot":                  true,
		"txid_snapshot_xip":                      true,
		"txid_snapshot_xmax":                     true,
		"txid_snapshot_xmin":                     true,
		"txid_status":                            true,
		"txid_visible_in_snapshot":               true,
		"unicode_assigned":                       true,
		"unicode_version":                        true,
		"unistr":                                 true,
		"unnest":                                 true,
		"upper":                                  true,
		"upper_inc":                              true,
		"upper_inf":                              true,
		"user":                                   true,
		"uuid_extract_timestamp":                 true,
		"uuid_extract_version":                   true,
		"var_pop":                                true,
		"var_samp":                               true,
		"variance":                               true,
		"version":                                true,
		"websearch_to_tsquery":                   true,
		"width":                                  true,
		"width_bucket":                           true,
		"xml_is_well_formed":                     true,
		"xml_is_well_formed_content":             true,
		"xml_is_well_formed_document":            true,
		"xmlagg":                                 true,
		"xmlcomment":                             true,
		"xmlconcat":                              true,
		"xmlelement":                             true,
		"xmlexists":                              true,
		"xmlforest":                              true,
		"xmlparse":                               true,
		"xmlpi":                                  true,
		"xmlroot":                                true,
		"xmlserialize":                           true,
		"xmltable":                               true,
		"xmltext":                                true,
		"xpath":                                  true,
		"xpath_exists":                           true,
	}

	// systemViews is the list of system views that we will exclude from the schema sync.
	// https://www.postgresql.org/docs/16/views.html
	systemViews = map[string]bool{
		"pg_available_extensions":         true,
		"pg_available_extension_versions": true,
		"pg_backend_memory_contexts":      true,
		"pg_config":                       true,
		"pg_cursors":                      true,
		"pg_file_settings":                true,
		"pg_group":                        true,
		"pg_hba_file_rules":               true,
		"pg_ident_file_mappings":          true,
		"pg_indexes":                      true,
		"pg_locks":                        true,
		"pg_matviews":                     true,
		"pg_policies":                     true,
		"pg_prepared_statements":          true,
		"pg_prepared_xacts":               true,
		"pg_publication_tables":           true,
		"pg_replication_origin_status":    true,
		"pg_replication_slots":            true,
		"pg_roles":                        true,
		"pg_rules":                        true,
		"pg_seclabels":                    true,
		"pg_sequences":                    true,
		"pg_settings":                     true,
		"pg_shadow":                       true,
		"pg_shmem_allocations":            true,
		"pg_stats":                        true,
		"pg_stats_ext":                    true,
		"pg_stats_ext_exprs":              true,
		"pg_tables":                       true,
		"pg_timezone_abbrevs":             true,
		"pg_timezone_names":               true,
		"pg_user":                         true,
		"pg_user_mappings":                true,
		"pg_views":                        true,
		// https://www.postgresql.org/docs/current/contrib.html
		"pg_stat_statements": true,
	}

	// systemSchemas is the list of system schemas that we will exclude from the schema sync.
	systemSchemas = map[string]bool{
		"information_schema":       true,
		"pg_catalog":               true,
		"pg_toast":                 true,
		"rw_catalog":               true,
		"timescaledb_information":  true,
		"timescaledb_experimental": true,
		"_timescaledb_cache":       true,
		"_timescaledb_catalog":     true,
		"_timescaledb_internal":    true,
		"_timescaledb_config":      true,
		"squeeze":                  true,
		// citus extension
		"citus":          true,
		"citus_internal": true,
		// citus columnar extension
		"columnar":          true,
		"columnar_internal": true,
		// pg_cron extension
		"cron": true,
		// pg_partman extension
		"partman": true,
	}

	// systemTables is the list of system tables that we will exclude from the schema sync.
	// https://www.postgresql.org/docs/16/catalogs.html
	systemTables = map[string]bool{
		"pg_aggregate":               true,
		"pg_am":                      true,
		"pg_amop":                    true,
		"pg_amproc":                  true,
		"pg_attrdef":                 true,
		"pg_attribute":               true,
		"pg_authid":                  true,
		"pg_auth_members":            true,
		"pg_cast":                    true,
		"pg_class":                   true,
		"pg_collation":               true,
		"pg_constraint":              true,
		"pg_conversion":              true,
		"pg_database":                true,
		"pg_db_role_setting":         true,
		"pg_default_acl":             true,
		"pg_depend":                  true,
		"pg_description":             true,
		"pg_enum":                    true,
		"pg_event_trigger":           true,
		"pg_extension":               true,
		"pg_foreign_data_wrapper":    true,
		"pg_foreign_server":          true,
		"pg_foreign_table":           true,
		"pg_index":                   true,
		"pg_inherits":                true,
		"pg_init_privs":              true,
		"pg_language":                true,
		"pg_largeobject":             true,
		"pg_largeobject_metadata":    true,
		"pg_namespace":               true,
		"pg_opclass":                 true,
		"pg_operator":                true,
		"pg_opfamily":                true,
		"pg_parameter_acl":           true,
		"pg_partitioned_table":       true,
		"pg_policy":                  true,
		"pg_proc":                    true,
		"pg_publication":             true,
		"pg_publication_namespace":   true,
		"pg_publication_rel":         true,
		"pg_range":                   true,
		"pg_replication_origin":      true,
		"pg_rewrite":                 true,
		"pg_seclabel":                true,
		"pg_sequence":                true,
		"pg_shdepend":                true,
		"pg_shdescription":           true,
		"pg_shseclabel":              true,
		"pg_statistic":               true,
		"pg_statistic_ext":           true,
		"pg_statistic_ext_data":      true,
		"pg_subscription":            true,
		"pg_subscription_rel":        true,
		"pg_tablespace":              true,
		"pg_transform":               true,
		"pg_trigger":                 true,
		"pg_ts_config":               true,
		"pg_ts_config_map":           true,
		"pg_ts_dict":                 true,
		"pg_ts_parser":               true,
		"pg_ts_template":             true,
		"pg_type":                    true,
		"pg_user_mapping":            true,
		"pg_stat_activity":           true,
		"pg_stat_replication":        true,
		"pg_stat_replication_slots":  true,
		"pg_stat_wal_receiver":       true,
		"pg_stat_recovery_prefetch":  true,
		"pg_stat_subscription":       true,
		"pg_stat_subscription_stats": true,
		"pg_stat_ssl":                true,
		"pg_stat_gssapi":             true,
		"pg_stat_archiver":           true,
		"pg_stat_bgwriter":           true,
		"pg_stat_wal":                true,
		"pg_stat_database":           true,
		"pg_stat_database_conflicts": true,
		"pg_stat_all_tables":         true,
		"pg_stat_all_indexes":        true,
		"pg_statio_all_tables":       true,
		"pg_statio_all_indexes":      true,
		"pg_statio_all_sequences":    true,
		"pg_stat_user_functions":     true,
		"pg_stat_slru":               true,
	}

	// SystemSchemaWhereClause is an optimization for getting less schema objects.
	SystemSchemaWhereClause = func() string {
		var schemas []string
		for schema := range systemSchemas {
			schemas = append(schemas, fmt.Sprintf("'%s'", schema))
		}
		return strings.Join(schemas, ",")
	}()
)

func IsSystemUser(user string) bool {
	return strings.HasPrefix(user, "alloydb")
}

func IsSystemDatabase(database string) bool {
	_, ok := systemDatabases[database]
	return ok
}

func IsSystemSchema(schema string) bool {
	_, ok := systemSchemas[schema]
	if ok {
		return true
	}
	if strings.HasPrefix(schema, "pg_temp") {
		return true
	}
	if strings.HasPrefix(schema, "pg_toast") {
		return true
	}
	return false
}

func IsSystemTable(table string) bool {
	_, ok := systemTables[table]
	return ok
}

func IsSystemView(view string) bool {
	if _, ok := systemViews[view]; ok {
		return true
	}
	if strings.HasPrefix(view, "g_columnar_") {
		return true
	}
	if strings.HasPrefix(view, "google_db_advisor_") {
		return true
	}
	if strings.HasPrefix(view, "g_agg_stat_") {
		return true
	}
	if strings.HasPrefix(view, "g_agg_stat_") {
		return true
	}
	if strings.HasPrefix(view, "hypopg") {
		return true
	}
	return false
}

func IsSystemFunction(function string, definition string) bool {
	_, ok := systemFunctions[strings.ToLower(function)]
	if !ok {
		// Some extension and rds builtin functions.
		if strings.HasPrefix(function, "g_columnar_") {
			return true
		}
		if strings.HasPrefix(function, "google_columnar_") {
			return true
		}
		if strings.HasPrefix(function, "google_db_advisor_") {
			return true
		}
		if strings.HasPrefix(function, "g_agg_stat_") {
			return true
		}
		if strings.HasPrefix(function, "hypopg") {
			return true
		}
		if function == "pg_stat_statements_wrapper" {
			return true
		}
		if strings.Contains(definition, "$libdir/timescaledb") {
			return true
		}
		return false
	}
	return true
}
